package com.example.roam.ui.activity;
import android.Manifest;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.example.roam.ui.adpter.TagEditAdapter;
import com.example.roam.api.Api;
import com.example.roam.api.HttpUpload;
import com.example.roam.R;
import com.example.roam.model.gson.UserSpaceImgEntity;
import com.example.roam.utils.Constans;
import com.example.roam.utils.HttpUtil;
import com.example.roam.utils.LogUtils;
import com.example.roam.utils.StatusBarUtils;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;

import jp.wasabeef.richeditor.RichEditor;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
public class UploadDiaryActivity extends AppCompatActivity implements View.OnClickListener{
    private ImageView  img_back , img_write ,img_t1 , img_t2 , tag_add;
    private ArrayList<Uri> mSelected;
    private HorizontalScrollView scrollView;
    private ImageView txt_bold,txt_italic,txt_underline,txt_insert_image,txt_indent,txt_outdent,txt_numbers,txt_h1,txt_h2,txt_h3,txt_h4,txt_h5 ,txt_html;
    private ImageView add_title,img_add;
    private EditText edt_title;
    private RichEditor richEditor;
    private Retrofit retrofit;
    private static final int RESULT_CODE_TAG_ADD = 200;
    private static final String TAG = "UploadDiaryActivity";
    private static final int REQUEST_CODE_CHOOSE = 100;
    private GridView gridViewTag;
    private TagEditAdapter tagEditAdapter;
    private ArrayList<String> dataArray;
    private LinearLayout ly_title_container , add_insert_img_container;
    private RelativeLayout option_push_container;
    private boolean isHideLayoutTitleContainer = false;
    private TextView txt_cancel ,txt_push;
    // 广场和个人空间的无限加载     // 点赞刷新

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
        setContentView(R.layout.activity_upload_diary);
        StatusBarUtils.setWindowStatusBarColor(this, R.color.purple_500);//设置状态栏颜色为银白色
        iniView();
        iniData();
        iniEvent();
    }

    public void iniView(){
        img_add = this.findViewById(R.id.img_add);
        txt_push = this.findViewById(R.id.txt_push);
        edt_title = this.findViewById(R.id.edt_title);
        add_title = this.findViewById(R.id.tag_add);
        img_write = this.findViewById(R.id.img_write);
        img_back = this.findViewById(R.id.img_back);
        img_t1 = this.findViewById(R.id.img_t1);
        img_t2 = this.findViewById(R.id.img_t2);
        scrollView = this.findViewById(R.id.scrollView);
        txt_bold = this.findViewById(R.id.txt_bold);
        txt_italic = this.findViewById(R.id.txt_italic);
        txt_underline = this.findViewById(R.id.txt_underline);
        txt_insert_image = this.findViewById(R.id.txt_insert_image);
        txt_indent = this.findViewById(R.id.txt_indent);
        txt_outdent = this.findViewById(R.id.txt_outdent);
        txt_numbers = this.findViewById(R.id.txt_numbers);
        txt_h1 = this.findViewById(R.id.txt_h1);
        txt_h2 = this.findViewById(R.id.txt_h2);
        txt_h3 = this.findViewById(R.id.txt_h3);
        txt_h4 = this.findViewById(R.id.txt_h4);
        txt_h5 = this.findViewById(R.id.txt_h5);
        txt_html = this.findViewById(R.id.txt_html);
        tag_add = this.findViewById(R.id.tag_add);
        richEditor = this.findViewById(R.id.rich);
        gridViewTag = this.findViewById(R.id.gridview_tag);
        ly_title_container = this.findViewById(R.id.ly_title_container);
        tagEditAdapter = new TagEditAdapter(this,1);
        dataArray = new ArrayList<>();
        add_insert_img_container = this.findViewById(R.id.add_insert_img_container);
        option_push_container = this.findViewById(R.id.option_push_container);
        txt_cancel = findViewById(R.id.txt_cancel);
    }

    public void iniData(){
        // 复习android，复习Spring-MVC , 了解现阶段项目规划 ，编写额外的接口和论坛对接（标注自己新实现的代码）
        richEditor.setEditorHeight(500);
        richEditor.setPadding(10,10,10,0);
        richEditor.setFontSize(16);
        richEditor.setPlaceholder("输入文本....");
        richEditor.setInputEnabled(true);
        gridViewTag.setAdapter(tagEditAdapter);
    }

    public void iniEvent(){
        img_add.setOnClickListener(this);
        txt_push.setOnClickListener(this);
        txt_cancel.setOnClickListener(this);
        img_back.setOnClickListener(this);
        img_write.setOnClickListener(this);
        txt_bold.setOnClickListener(this);
        txt_italic.setOnClickListener(this);
        txt_underline.setOnClickListener(this);
        txt_underline.setOnClickListener(this);
        txt_insert_image.setOnClickListener(this);
        txt_indent.setOnClickListener(this);
        txt_outdent.setOnClickListener(this);
        txt_numbers.setOnClickListener(this);
        txt_h1.setOnClickListener(this);
        txt_h2.setOnClickListener(this);
        txt_h3.setOnClickListener(this);
        txt_h4.setOnClickListener(this);
        txt_h5.setOnClickListener(this);
        txt_html.setOnClickListener(this);
        add_title.setOnClickListener(this);
        tag_add.setOnClickListener(this);
        richEditor.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if( hasFocus == true ){
                    ly_title_container.setVisibility(View.GONE);
                    add_insert_img_container.setVisibility(View.GONE);
                    option_push_container.setVisibility(View.GONE);
                    isHideLayoutTitleContainer = true;
                }
            }
        });
    }

    /**
     *  上传html网页
     * */

    public void postHtml(){
        int spaceReleaseType = 4;  // 控制不同类型： 介绍，spaceReleaseType 1  旅游 spaceReleaseType 2  民俗 spaceReleaseType 3  广场 spaceReleaseType 4
        if(!edt_title.getText().toString().trim().equals("")) {
            String[] tags = new String[dataArray.size()];
            for (int i = 0; i < dataArray.size(); i++) {
                tags[i] = dataArray.get(i);
            }
            retrofit = new Retrofit.Builder().baseUrl(HttpUtil.ADDRESS).build();
            // 1  3 民俗 2 旅游
            retrofit.create(Api.class).postHtml(edt_title.getText().toString(), richEditor.getHtml(), spaceReleaseType, 1, Constans.u_id, 1, tags, HttpUtil.COOKIE).enqueue(new Callback<ResponseBody>() {
                @Override
                public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                    try {
                        Log.i(TAG, "onResponse: " + response.body().string());

                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    UploadDiaryActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            Intent intent = new Intent(UploadDiaryActivity.this, ForumActivity.class);
                            intent.putExtra("url", "https://www.baidu.com");
                            startActivity(intent);
                        }
                    });
                }

                @Override
                public void onFailure(Call<ResponseBody> call, Throwable t) {
                    Log.i(TAG, "onFailure: 上传网页失败");
                }
            });
        }else {
            Toast.makeText(UploadDiaryActivity.this,"标题不可为空",Toast.LENGTH_SHORT).show();
        }

    }

    public static String getRealFilePath(final Context context, final Uri uri ) {
        if ( null == uri ) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if ( scheme == null )
            data = uri.getPath();
        else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
            data = uri.getPath();
        } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
            Cursor cursor = context.getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null );
            if ( null != cursor ) {
                if ( cursor.moveToFirst() ) {
                    int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA );
                    if ( index > -1 ) {
                        data = cursor.getString( index );
                    }
                }
                cursor.close();
            }
        }
        return data;
    }

    /**
     * 获取数据库表中的 _data 列，即返回Uri对应的文件路径
     * @return
     */
    private static String getDataColumn(Context context, Uri uri, String selection, String[] selectionArgs) {
        String path = null;
        String[] projection = new String[]{MediaStore.Images.Media.DATA};
        Cursor cursor = null;
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs, null);
            if (cursor != null && cursor.moveToFirst()) {
                int columnIndex = cursor.getColumnIndexOrThrow(projection[0]);
                path = cursor.getString(columnIndex);
            }
        } catch (Exception e) {
            if (cursor != null) {
                cursor.close();
            }
        }
        return path;
    }

    @Override
    public void onClick(View v) {
        switch ( v.getId()){
            case R.id.img_add:
                richEditor.focusEditor();
                requestPermission();
                Matisse.from(UploadDiaryActivity.this) //Activity
                        .choose(MimeType.ofAll()) //选择全部（包括视频）
                        .countable(true)  // 有序选择图片
                        .maxSelectable(9)  //最大选择数量为9
                        .gridExpectedSize(400)  //图片显示表格的大小
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                        .thumbnailScale(0.85f)  //缩放比率
                        .theme(R.style.Matisse_Zhihu) //主题  暗色主题 R.style.Matisse_Dracula
                        .imageEngine(new GlideEngine()) //加载方式
                        .forResult(REQUEST_CODE_CHOOSE); //结果返回码 ，在onActivityResult中获取

                break;
            case R.id.txt_push:
                postHtml();
                break;
            case R.id.txt_cancel:
                this.finish();
                break;
            case R.id.txt_bold:
                richEditor.setBold(); // 加粗 点击开启或者取消
                break;
            case R.id.txt_italic:
                richEditor.setItalic(); // 斜体
                break;
            case R.id.txt_underline:
                richEditor.setUnderline();
                break;
            case R.id.txt_insert_image:
                // 这里有一个问题，我应该获取设备的宽度来匹配图片的宽度
                // 或者说，改组件的宽度。可能这里是dp
                // 待解决：发布。基础页面，测试，图片选择，图片上传，颜色盘
//                richEditor.insertImage("http://106.55.50.79:8080/PageProject/img/self1.png","cat\" width="+390+"\"");
                // 一周时间完成--- 全部完成。
                richEditor.focusEditor();
                requestPermission();
                Matisse.from(UploadDiaryActivity.this) //Activity
                        .choose(MimeType.ofAll()) //选择全部（包括视频）
                        .countable(true)  // 有序选择图片
                        .maxSelectable(9)  //最大选择数量为9
                        .gridExpectedSize(400)  //图片显示表格的大小
                        .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                        .thumbnailScale(0.85f)  //缩放比率
                        .theme(R.style.Matisse_Zhihu) //主题  暗色主题 R.style.Matisse_Dracula
                        .imageEngine(new GlideEngine()) //加载方式
                        .forResult(REQUEST_CODE_CHOOSE); //结果返回码 ，在onActivityResult中获取

                // 或则是调出输入法
//                inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
                break;
            case R.id.txt_indent:
                richEditor.setIndent();
                break;
            case R.id.txt_outdent:
                richEditor.setOutdent();
                break;
            case R.id.txt_numbers:
                richEditor.setNumbers();
                break;
            case R.id.txt_h1:
                richEditor.setHeading(1);
                break;
            case R.id.txt_h2:
                richEditor.setHeading(2);
                break;
            case R.id.txt_h3:
                richEditor.setHeading(3);
                break;
            case R.id.txt_h4:
                richEditor.setHeading(4);
                break;
            case R.id.txt_h5:
                richEditor.setHeading(5);
                break;
            case R.id.txt_html:

                break;
            case R.id.img_back:
                if( isHideLayoutTitleContainer ){
                    isHideLayoutTitleContainer = false;
                    ly_title_container.setVisibility(View.VISIBLE);
                    add_insert_img_container.setVisibility(View.VISIBLE);
                    option_push_container.setVisibility(View.VISIBLE);
                    InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                    inputMethodManager.hideSoftInputFromWindow(UploadDiaryActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    richEditor.clearFocus();

                }else {
                    UploadDiaryActivity.this.finish();
                }
                break;
            case R.id.img_write:
                postHtml();
                break;
            case R.id.tag_add:
                Intent intent = new Intent(UploadDiaryActivity.this,TagChooseActivity.class);
                intent.putStringArrayListExtra("dataArray",dataArray);
                startActivityForResult(intent, RESULT_CODE_TAG_ADD);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            mSelected = (ArrayList<Uri>) Matisse.obtainResult(data);
            Log.d("Matisse", "mSelected: " + mSelected);
            String realFilePath = getRealFilePath(this, mSelected.get(0));
            postImage(realFilePath);
            Toast.makeText(this,"图片上传较慢，请稍等",Toast.LENGTH_SHORT).show();
        }else if( requestCode == RESULT_CODE_TAG_ADD){
            dataArray = data.getStringArrayListExtra("dataArray");
            tagEditAdapter.setDataArray(dataArray);
            LogUtils.i(UploadDiaryActivity.class,"stringDataArray: "+dataArray.toString());
        }

    }

    public void postImage(String realFilePath){
        File file = new File(realFilePath);
        RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpeg"),file);
        MultipartBody.Part part = MultipartBody.Part.createFormData("uploadFile",file.getName(),requestBody);
        Retrofit retrofit = new Retrofit.Builder().addConverterFactory(GsonConverterFactory.create()).baseUrl(HttpUtil.FILE_ADDRESS).build();
        retrofit.create(HttpUpload.class).uploadUserSpaceImg(part).enqueue(new Callback<UserSpaceImgEntity>() {
            @Override
            public void onResponse(Call<UserSpaceImgEntity> call, Response<UserSpaceImgEntity> response) {
                richEditor.insertImage(response.body().getData().getUrl(),"cat\" width="+370+"\"");
//                richEditor.insertImage(response.body().getData().getUrl(),"cat\" width="+370+">/&gt");
//              richEditor.insertImage(response.body().getData().getUrl(),"cat\" width="+370+">/&gt");
//                <img src="http://teaculture-001.oss-cn-chengdu.aliyuncs.com/userSpaceImg/20220507/3c2a16b64c4e40b4a4e554dc2f8c9dbf.jpeg" alt="cat" width="370&quot;"><br"></br">
            }

            @Override
            public void onFailure(Call<UserSpaceImgEntity> call, Throwable t) {
                Log.i(TAG, "onFailure: 获取地址失败！");
            }

        });
    }



    // 请求 外部存储读和写权限
    public void requestPermission(){
        if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED) ){
            if(ActivityCompat.checkSelfPermission(UploadDiaryActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != 0 ){
                ActivityCompat.requestPermissions(UploadDiaryActivity.this,new String[]{Manifest.permission.READ_EXTERNAL_STORAGE,Manifest.permission.WRITE_EXTERNAL_STORAGE},10);
            }
        }
    }

    // 2. 往SQLite添加个人说说数据
    public void insertZoneTable(){
        // z_content , z_img1 , z_img2 , uid2
    }

    /**
     * @param uri the Uri to check
     * @return Whether the Uri authority is MediaProvider
     */
    private static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri the Uri to check
     * @return Whether the Uri authority is DownloadsProvider
     */
    private static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

}